﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMSGSC.BLL;
using System.Linq;
using System.IO;
using DevExpress.XtraEditors.Controls;
using System.Data.Linq;
using DevExpress.XtraGrid.Columns;
using PMSGSC.DAL;
using PMSGSC.Common;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Localization;
using System.Diagnostics;


namespace PMSGSC.App
{
    public partial class frmCertificate : DevExpress.XtraEditors.XtraForm
    {
        private bool valueChanged;

        // Init
        public frmCertificate(List<Certificate> dataSource)
        {
            InitializeComponent();
            typeCertificateBindingSource.DataSource = CertificateType_BLL.GetAll(frmMain.ship.Ship_ID);

            if (null == dataSource)
                certificateBindingSource.DataSource = Certificate_BLL.GetDataByShipID(frmMain.ship.Ship_ID, valueChanged);
            else
                certificateBindingSource.DataSource = dataSource;
        }

        // Khai báo trạng thái mặc định 
        private Status statusCertificate = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private Certificate certificate = new Certificate();
        //Hiển thị số thứ tự của gridview
        private void gridViewA_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        // Sự kiện cập nhật dữ liệu xuống database
        private void gridViewA_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SaveCertificateToDatabase();
        }
        // Read file from filename
        private byte[] StreamFile(string fileName)
        {
            // Open file
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            // ByteArray
            byte[] ImageData = new byte[fs.Length];

            // Read block of bytes
            fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

            // Close it
            fs.Close();

            // Return the byte data
            return ImageData;
        }
        // Convert to File
        public bool ByteArrayToFile(string fileName, byte[] byteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream fileStream = new System.IO.FileStream
                    (fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                // Writes a block of bytes
                fileStream.Write(byteArray, 0, byteArray.Length);

                // Close file stream
                fileStream.Close();

                return true;
            }
            catch (Exception ex)
            {
                //
            }
            return false;
        }
        // When current certificate value change
        private void certificateBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            valueChanged = true;
        }
        // Click Open button
        private void repositoryItemButtonEdit2_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            try
            {
                Opencertificate();
            }
            catch { }
        }
        // Click Upload button
        private void btnUploadFile_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "Select one file upload";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog.InitialDirectory + openFileDialog.FileName;
                FileInfo fileInfo = new FileInfo(fileName);
                long sizeFile = fileInfo.Length / 1000;
                if (sizeFile <= 3000)
                {
                    string extension = Path.GetExtension(fileName);
                    certificate.Extension = extension;
                    byte[] fileByteArray = StreamFile(fileName);
                    // Converts it to Binary
                    // it can be done inside the method as well
                    Binary fileBinary = new Binary(fileByteArray);
                    certificate.ContentFile = fileBinary;
                    GridColumn certificateExtension = gridView18.Columns["Extension"];
                    extension = extension.ToUpper();
                    gridView18.SetRowCellValue(gridView18.FocusedRowHandle, certificateExtension, extension);
                }
                else
                {
                    XtraMessageBox.Show("The size file  must be less than 3M ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }

        }
        // Save certificate down database
        private void SaveCertificateToDatabase()
        {
            frmProcessBar pb = new frmProcessBar();
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                LoadSkinToForm();
                pb.ShowDialog();
            }
            ));

            if (statusCertificate == Status.Update)
            {
                if (XtraMessageBox.Show("Do you want to save changes?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    thread.Start();
                    bool result = Certificate_BLL.Update(certificate);

                    if (pb.InvokeRequired)
                        pb.BeginInvoke(new Action(() => pb.Close()));

                    if (!result)
                        XtraMessageBox.Show("Update Unsuccess !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    else
                        XtraMessageBox.Show("Update Success !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                certificateBindingSource.DataSource = Certificate_BLL.GetDataByShipID(1, valueChanged);
                valueChanged = false;

            }

            if (statusCertificate == Status.New)
            {
                thread.Start();
                bool result = Certificate_BLL.Insert(certificate);

                if (pb.InvokeRequired)
                    pb.BeginInvoke(new Action(() => pb.Close()));

                if (!result)
                {
                    XtraMessageBox.Show("Insert Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                statusCertificate = Status.Update;

            }
        }
        // Load skin
        private static void LoadSkinToForm()
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.LookAndFeel.DefaultLookAndFeel obj = new DevExpress.LookAndFeel.DefaultLookAndFeel();
            try
            {
                LookAndFeelSettings.Load("LookAndFeelSettings.dat");
            }
            catch
            {
                obj.LookAndFeel.SetSkinStyle("Blue");
            }
        }
        // Delete certificate
        private void DeleteCertificate(NavigatorButtonClickEventArgs e)
        {
            DeleteCertificateFinal();
            e.Handled = true;
        }
        // delete final
        private void DeleteCertificateFinal()
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Certificate?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                certificate = certificateBindingSource.Current as Certificate;
                bool result = Certificate_BLL.Delete(certificate);
                if (!result)
                {
                    XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                certificateBindingSource.DataSource = Certificate_BLL.GetDataByShipID(1, valueChanged);

                valueChanged = false;
            }
        }

        // Sự kiện nhân phím delete sảy ra
        private void gridViewA_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DeleteCertificateFinal();
            }
        }

        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewA_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            statusCertificate = Status.New;
        }

        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewA_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = (GridView)sender;

            GridColumn certificateCode = view.Columns["CodeCertificate"];
            GridColumn certificateContent = view.Columns["ContentFile"];
            GridColumn certificateType = view.Columns["TypeCertificate_ID"];

            if (null == view.GetRowCellValue(e.RowHandle, certificateType))
            {
                e.Valid = false;
                view.FocusedColumn = certificateType;
                e.ErrorText = "Please enter the Certificate Type. ";
                view.SetColumnError(certificateType, "Certificate Type is not empty");
                return;
            }

            if (null == view.GetRowCellValue(e.RowHandle, certificateCode))
            {
                e.Valid = false;
                view.FocusedColumn = certificateCode;
                e.ErrorText = "Please enter the Certificate Code. ";
                view.SetColumnError(certificateCode, "Certificate Code is not empty");
                return;
            }

            if (null == view.GetRowCellValue(e.RowHandle, certificateContent))
            {
                e.Valid = false;
                e.ErrorText = "Please upload one file into table! ";
                return;
            }

            certificate = certificateBindingSource.Current as Certificate;
            if (Certificate_BLL.IsExits(certificate))
            {
                e.Valid = false;
                view.FocusedColumn = certificateCode;
                e.ErrorText = "Certificate Code is exits. ";
                view.SetColumnError(certificateCode, "Certificate Code is exits");
                return;
            }

        }
        // current position change
        private void certificateBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            certificate = certificateBindingSource.Current as Certificate;
        }

        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewA_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {

            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl12.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    certificateBindingSource.DataSource = Certificate_BLL.GetDataByShipID(1, true);

                    valueChanged = false;
                }
            }
        }

        // Đặt lại trạng thái update 
        private void gridViewA_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusCertificate = Status.Update;
            }
        }
        // Open certificate 
        private void Opencertificate()
        {
            if (gridView18.FocusedRowHandle != GridControl.NewItemRowHandle)
            {
                string Address = Application.StartupPath + "\\Attachment\\";
                Directory.CreateDirectory(Address);
                certificate = certificateBindingSource.Current as Certificate;
                Certificate attach = Certificate_BLL.GetDataById(certificate.Certificate_ID);

                if (null != attach)
                {
                    string fileName = attach.Name + attach.Extension;
                    Address += fileName;
                    if (ByteArrayToFile(Address, attach.ContentFile.ToArray()))
                    {
                        try
                        {
                            Process.Start(Address);
                        }
                        catch { }
                    }
                }
            }
        }
        // Only input number
        private static void OnlyInputNumberic(KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }
        // Key Press event
        private void txtNotice_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }
        // Certificate type change value
        private void gluTypeCertificate_EditValueChanging(object sender, ChangingEventArgs e)
        {
            try
            {
                ((Certificate)gridView18.GetFocusedRow()).TypeCertificate = BaseDAL.DB.TypeCertificates.Single(n => n.TypeCertificate_ID == (int)e.NewValue);
            }
            catch(Exception ex)
            { 
                //
            }
        }

        private void certificateBindingSource_CurrentChanged_1(object sender, EventArgs e)
        {
            certificate = certificateBindingSource.Current as Certificate;
        }

        private void gridControl12_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.Remove:
                    DeleteCertificate(e);
                    break;
            }
        }
    }
}